<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Oauth2, 博客 blog">
    <meta name="description" content="熊猫小二的博客  xmxe&#39;s blog">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- 为了引用qq空间图床文件 -->
    <meta name="referrer" content="no-referrer">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Oauth2 | 熊猫小二</title>
    <link rel="icon" type="image/x-icon, image/vnd.microsoft.icon" href="/blog/favicon.ico">
    <link rel="stylesheet" type="text/css" href="/blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/my.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/loading.css">

    <script src="/blog/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>



   
<style>
    body{
       background-image: url(/blog/medias/cover.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    
  <div id="loading-box">
    <div class="loading-left-bg"></div>
    <div class="loading-right-bg"></div>
    <div class="spinner-box">
      <div class="configure-border-1">
        <div class="configure-core"></div>
      </div>
      <div class="configure-border-2">
        <div class="configure-core"></div>
      </div>
      <div class="loading-word">加载中...</div>
    </div>
  </div>
  <!-- 页面加载动画 -->
  <script>
    $(document).ready(function () {
      // document.body.style.overflow = 'auto';
      document.getElementById('loading-box').classList.add("loaded")
    })
  </script>

    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/blog/" class="waves-effect waves-light">
                    
                        <img src="/blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">熊猫小二</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-book" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>归档</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/about">
          
          <i class="fas fa-star-of-david" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>主页</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/gallery">
          
          <i class="fas fa-images" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  
    <li>
      <a class="waves-effect waves-light" onclick="switchNightMode()">
        <i id="sum-moon-icon" class="fas fa-sun" style="zoom:0.65;" title="切换主题"></i>
      </a>
    </li>
  
  
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
          <img src="/blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">熊猫小二</div>
        <div class="logo-desc">
            
            熊猫小二的博客  xmxe&#39;s blog
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
		          <span>归档</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-user-circle"></i>
			
			关于
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/about " style="margin-left:75px">
				  
				   <i class="fa fas fa-star-of-david" style="position: absolute;left:50px" ></i>
			      
		          <span>主页</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/gallery " style="margin-left:75px">
				  
				   <i class="fa fas fa-images" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/blog/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/blog/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/blog/medias/featureimages/8.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 id="post-title" class="description center-align post-title"></h1>

                    
                        <!-- <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script> -->
                        <script>
                            var typedObj = new Typed("#post-title", {
                                strings: [ 'Oauth2' ],
                                startDelay: 300,
                                typeSpeed: 70,
                                loop: false,
                                backSpeed: 50,
                                showCursor: true
                            });
                        </script>
                    
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
        background-color: rgb(255, 255, 255,0.7);
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
        max-height: 480px;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/blog/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/" class="post-category">
                                技术栈
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/blog/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>demo<br>fork from <a target="_blank" rel="noopener" href="https://github.com/lenve/oauth2-samples">oauth2-samples</a></p>
<blockquote>
<table>
<thead>
<tr>
<th align="left">Demo</th>
<th align="left">文章</th>
</tr>
</thead>
<tbody><tr>
<td align="left">authorization_code</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/GXMQI59U6uzmS-C0WQ5iUw">这个案例写出来，还怕跟面试官扯不明白OAuth2登录流程？</a></td>
</tr>
<tr>
<td align="left">client_credentials</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/33Oxu6YMjwco3WRE07_IiQ">死磕OAuth2，教练我要学全套的！</a></td>
</tr>
<tr>
<td align="left">implicit</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/33Oxu6YMjwco3WRE07_IiQ">死磕OAuth2，教练我要学全套的！</a></td>
</tr>
<tr>
<td align="left">password</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/33Oxu6YMjwco3WRE07_IiQ">死磕OAuth2，教练我要学全套的！</a></td>
</tr>
<tr>
<td align="left">authorization_code_redis</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/cGopy8hDPtkn8Q7HUYabbA">OAuth2令牌存入Redis</a></td>
</tr>
<tr>
<td align="left">jwt</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/xEIWTduDqQuGL7lfiP735w">让OAuth2和JWT在一起愉快玩耍</a></td>
</tr>
<tr>
<td align="left">oauth2-sso</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/EyAMTbKPqNNnEtZACIsMVw">Spring Boot+OAuth2，一个注解搞定单点登录！</a></td>
</tr>
<tr>
<td align="left">github_login</td>
<td align="left"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/tq4Q306J3hJFEtGL1EpOBA">分分钟让自己的网站接入GitHub第三方登录功能</a></td>
</tr>
</tbody></table>
</blockquote>
</blockquote>
<hr>
<h3 id="OAuth2-0的四种模式"><a href="#OAuth2-0的四种模式" class="headerlink" title="OAuth2.0的四种模式"></a>OAuth2.0的四种模式</h3><h4 id="授权码模式"><a href="#授权码模式" class="headerlink" title="授权码模式"></a>授权码模式</h4><p>这种方式是最常用的流程，安全性也最高，它适用于那些有后端的Web应用。授权码通过前端传送，令牌则是储存在后端，而且所有与资源服务器的通信都在后端完成。这样的前后端分离，可以避免令牌泄漏。令牌获取的流程如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/19cc2hfD2rCpPJB83SvgzosiboTJxftAhibgOZffmU9RnmNUusomvBtoUKaxEXIU1df2icbUZOwSUeG4G0DxWgjtQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="授权码模式"><br>上图中涉及到两个角色，分别是客户端、认证中心，客户端负责拿令牌，认证中心负责发放令牌。但是不是所有客户端都有权限请求令牌的，需要事先在认证中心申请，比如微信并不是所有网站都能直接接入，而是要去微信后台开通这个权限。至少要提前向认证中心申请的几个参数如下：</p>
<ul>
<li><strong>client_id</strong>：客户端唯一id，认证中心颁发的唯一标识</li>
<li><strong>client_secret</strong>：客户端的秘钥，相当于密码</li>
<li><strong>scope</strong>：客户端的权限</li>
<li><strong>redirect_uri</strong>：授权码模式使用的跳转uri，需要事先告知认证中心。</li>
</ul>
<p><strong>请求授权码</strong></p>
<p>客户端需要向认证中心拿到授权码，比如第三方登录使用微信，扫一扫登录那一步就是向微信的认证中心获取授权码。请求的url如下：</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;oauth&#x2F;authorize?client_id&#x3D;&amp;response_type&#x3D;code&amp;scope&#x3D;&amp;redirect_uri&#x3D;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>上述这个url中携带的几个参数如下：</p>
<ul>
<li><strong>client_id</strong>：客户端的id，这个由认证中心分配，并不是所有的客户端都能随意接入认证中心</li>
<li><strong>response_type</strong>：固定值为code，表示要求返回授权码。</li>
<li><strong>scope</strong>：表示要求的授权范围，客户端的权限</li>
<li><strong>redirect_uri</strong>：跳转的uri，认证中心同意或者拒绝授权跳转的地址，如果同意会在uri后面携带一个code&#x3D;xxx，这就是授权码</li>
</ul>
<p><strong>返回授权码</strong></p>
<p>请求授权码之后，认证中心会要求登录、是否同意授权，用户同意授权之后直接跳转到redirect_uri（这个需要事先在认证中心申请配置），授权码会携带在这个地址后面，如下：</p>
<pre class="line-numbers language-none"><code class="language-none">http:&#x2F;&#x2F;xxxx?code&#x3D;NMoj5y<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>上述链接中的NMoj5y就是授权码了。</p>
<p><strong>请求令牌</strong></p>
<p>客户端拿到授权码之后，直接携带授权码发送请求给认证中心获取令牌，请求的url如下：</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;oauth&#x2F;token?
 client_id&#x3D;&amp;
 client_secret&#x3D;&amp;
 grant_type&#x3D;authorization_code&amp;
 code&#x3D;NMoj5y&amp;
 redirect_uri&#x3D;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>相同的参数同上，不同参数解析如下：</p>
<ul>
<li>grant_type：授权类型，授权码固定的值为authorization_code</li>
<li>code：这个就是上一步获取的授权码</li>
</ul>
<p><strong>返回令牌</strong></p>
<p>认证中心收到令牌请求之后，通过之后，会返回一段JSON数据，其中包含了令牌access_token，如下：</p>
<pre class="line-numbers language-json" data-language="json"><code class="language-json"><span class="token punctuation">&#123;</span>    
  <span class="token property">"access_token"</span><span class="token operator">:</span><span class="token string">"ACCESS_TOKEN"</span><span class="token punctuation">,</span>
  <span class="token property">"token_type"</span><span class="token operator">:</span><span class="token string">"bearer"</span><span class="token punctuation">,</span>
  <span class="token property">"expires_in"</span><span class="token operator">:</span><span class="token number">2592000</span><span class="token punctuation">,</span>
  <span class="token property">"refresh_token"</span><span class="token operator">:</span><span class="token string">"REFRESH_TOKEN"</span><span class="token punctuation">,</span>
  <span class="token property">"scope"</span><span class="token operator">:</span><span class="token string">"read"</span><span class="token punctuation">,</span>
  <span class="token property">"uid"</span><span class="token operator">:</span><span class="token number">100101</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>access_token则是颁发的令牌，refresh_token是刷新令牌，一旦令牌失效则携带这个令牌进行刷新。</p>
<h4 id="简化模式"><a href="#简化模式" class="headerlink" title="简化模式"></a>简化模式</h4><p>这种模式不常用，主要针对那些无后台的系统，直接通过web跳转授权，流程如下图：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/19cc2hfD2rCpPJB83SvgzosiboTJxftAhxGsEsTxPIovmxbYqEqregcCE7o0h7fvcjkGSrdtXqUxFfs4EwqbegQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="简化模式"></p>
<p>这种方式把令牌直接传给前端，是很不安全的。因此，只能用于一些安全要求不高的场景，并且令牌的有效期必须非常短，通常就是会话期间（session）有效，浏览器关掉，令牌就失效了。</p>
<p><strong>请求令牌</strong></p>
<p>客户端直接请求令牌，请求的url如下：</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;oauth&#x2F;authorize?
  response_type&#x3D;token&amp;
  client_id&#x3D;CLIENT_ID&amp;
  redirect_uri&#x3D;CALLBACK_URL&amp;
  scope&#x3D;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个url正是授权码模式中获取授权码的url，各个参数解析如下：</p>
<ul>
<li><strong>client_id</strong>：客户端的唯一Id</li>
<li><strong>response_type</strong>：简化模式的固定值为token</li>
<li><strong>scope</strong>：客户端的权限</li>
<li><strong>redirect_uri</strong>：跳转的uri，这里后面携带的直接是令牌，不是授权码了。</li>
</ul>
<p><strong>返回令牌</strong></p>
<p>认证中心认证通过后，会跳转到redirect_uri，并且后面携带着令牌，链接如下：</p>
<pre class="line-numbers language-none"><code class="language-none">https:&#x2F;&#x2F;xxxx#token&#x3D;NPmdj5<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>token&#x3D;NPmdj5这一段后面携带的就是认证中心携带的，令牌为NPmdj5。</p>
<h4 id="密码模式"><a href="#密码模式" class="headerlink" title="密码模式"></a>密码模式</h4><p>密码模式也很简单，直接通过用户名、密码获取令牌，流程如下：<br><img src="https://mmbiz.qpic.cn/mmbiz_png/19cc2hfD2rCpPJB83SvgzosiboTJxftAhxGsEsTxPIovmxbYqEqregcCE7o0h7fvcjkGSrdtXqUxFfs4EwqbegQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="密码模式"></p>
<p><strong>请求令牌</strong></p>
<p>认证中心要求客户端输入用户名、密码，认证成功则颁发令牌，请求的url如下：</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;oauth&#x2F;token?
  grant_type&#x3D;password&amp;
  username&#x3D;&amp;
  password&#x3D;&amp;
  client_id&#x3D;&amp;
  client_secret&#x3D;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>参数解析如下：</p>
<ul>
<li><strong>grant_type</strong>：授权类型，密码模式固定值为password</li>
<li><strong>username</strong>：用户名</li>
<li><strong>password</strong>：密码</li>
<li><strong>client_id</strong>：客户端id</li>
<li><strong>client_secret</strong>：客户端的秘钥</li>
</ul>
<p><strong>返回令牌</strong></p>
<p>上述认证通过，直接返回JSON数据，不需要跳转，如下：</p>
<pre class="line-numbers language-json" data-language="json"><code class="language-json"><span class="token punctuation">&#123;</span>
  <span class="token property">"access_token"</span><span class="token operator">:</span><span class="token string">"ACCESS_TOKEN"</span><span class="token punctuation">,</span>
  <span class="token property">"token_type"</span><span class="token operator">:</span><span class="token string">"bearer"</span><span class="token punctuation">,</span>
  <span class="token property">"expires_in"</span><span class="token operator">:</span><span class="token number">2592000</span><span class="token punctuation">,</span>
  <span class="token property">"refresh_token"</span><span class="token operator">:</span><span class="token string">"REFRESH_TOKEN"</span><span class="token punctuation">,</span>
  <span class="token property">"scope"</span><span class="token operator">:</span><span class="token string">"read"</span><span class="token punctuation">,</span>
  <span class="token property">"uid"</span><span class="token operator">:</span><span class="token number">100101</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>access_token则是颁发的令牌，refresh_token是刷新令牌，一旦令牌失效则携带这个令牌进行刷新。</p>
<h4 id="客户端模式"><a href="#客户端模式" class="headerlink" title="客户端模式"></a>客户端模式</h4><p>适用于没有前端的命令行应用，即在命令行下请求令牌。<br>这种方式给出的令牌，是针对第三方应用的，而不是针对用户的，即有可能多个用户共享同一个令牌。流程如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/19cc2hfD2rCpPJB83SvgzosiboTJxftAhxGsEsTxPIovmxbYqEqregcCE7o0h7fvcjkGSrdtXqUxFfs4EwqbegQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="客户端模式"></p>
<p><strong>请求令牌</strong></p>
<p>请求的url为如下：</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;oauth&#x2F;token?
grant_type&#x3D;client_credentials&amp;
client_id&#x3D;&amp;
client_secret&#x3D;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>参数解析如下：</p>
<ul>
<li><strong>grant_type</strong>：授权类型，客户端模式固定值为client_credentials</li>
<li><strong>client_id</strong>：客户端id</li>
<li><strong>client_secret</strong>：客户端秘钥</li>
</ul>
<p><strong>返回令牌</strong></p>
<p>认证成功后直接返回令牌，格式为JSON数据，如下：</p>
<pre class="line-numbers language-json" data-language="json"><code class="language-json"><span class="token punctuation">&#123;</span>
    <span class="token property">"access_token"</span><span class="token operator">:</span> <span class="token string">"ACCESS_TOKEN"</span><span class="token punctuation">,</span>
    <span class="token property">"token_type"</span><span class="token operator">:</span> <span class="token string">"bearer"</span><span class="token punctuation">,</span>
    <span class="token property">"expires_in"</span><span class="token operator">:</span> <span class="token number">7200</span><span class="token punctuation">,</span>
    <span class="token property">"scope"</span><span class="token operator">:</span> <span class="token string">"all"</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="access-token-VS-refresh-token"><a href="#access-token-VS-refresh-token" class="headerlink" title="access_token VS refresh_token"></a>access_token VS refresh_token</h3><p><strong>介绍</strong></p>
<p>Token作为用户获取受保护资源的凭证，必须设置一个过期时间，否则一次登录便可永久使用，认证功能就失去了意义。但是矛盾在于：过期时间设置得太长，用户数据的安全性将大打折扣，过期时间设置得太短，用户就必须每隔一段时间重新登录，以获取新的凭证，这会极大挫伤用户的积极性。针对这一问题，我们可以利用Access &#x2F; Refresh Token这一概念来平衡Token安全性和用户体验。</p>
<p>众所周知,在OAuth 2.0授权协议中,有两个令牌token,分别是access_token和refresh_token。我们先看下面两者的介绍：access_token-访问令牌,它是一个用来访问受保护资源的凭证。refresh_token-刷新令牌,它是一个用来获取access token的凭证。这两个令牌的主要区别如下:</p>
<ul>
<li>access_token时效短,refresh_token时效长,比如access_token有效期1个小时,refresh_token有效期1天。</li>
<li>access_token是授权服务器一定颁发的,而refresh_token却是可选的。</li>
<li>access_token过期后,可以使用refresh_token重新获取,而refresh_token过期后就只能重新授权了,也没有refresh_refresh_token。</li>
<li>access_token和资源服务器和授权服务器交互,而refresh_token只和授权服务器交互。</li>
<li>access_token颁发后可以直接使用,而使用refresh_token需要客户端秘钥client_secret。</li>
</ul>
<p>简单来说：Access Token即“访问令牌”，是客户端向资源服务器换取资源的凭证；Refresh Token即“刷新令牌”，是客户端向认证服务器换取Access Token的凭证。</p>
<p>接下来,我们继续看两个令牌在下面场景的应用,假设有一个用户需要在后台管理界面上操作6个小时。</p>
<ol>
<li><p>颁发一个有效性很长的access_token,比如6个小时,或者可以更长,这样用户只需要刚开始登录一次,access_token可以一直使用,直到access_token过期,然后重复,这种是不安全的,access_token的时效太长,也就失去了本身的意义。</p>
</li>
<li><p>颁发一个1小时有效期的access_token,过期后重新登录授权,这样用户需要登录6次,安全倒是有了,但是用户体验极差。</p>
</li>
<li><p>颁发1小时有效期的access_token和6小时有效期的refresh_token,当access_token过期后（或者快要过期的时候）,使用refresh_token获取一个新的access_token,直到refresh_token过期,用户重新登录,这样整个过程中，用户只需要登录一次,用户体验好。<strong>access_token泄露了怎么办?没关系,它很快就会过期。refresh_token泄露了怎么办?没关系,使用refresh_token是需要客户端秘钥client_secret的</strong>。</p>
</li>
<li><p>用户登录后,在后台管理页面上操作1个小时后,离开了一段时间,然后5个小时后,回到管理页面继续操作,此时refresh_token有效期6个小时,一直没有过期,也就可以换取新的access_token,用户在这个过程中,可以不用重复登录。但是在一些安全要求较高的系统中,第二次操作是需要重新登录的,即使refresh_token没有过期,因为中间有几个小时,用户是没有操作的,系统猜测用户已离开,并关闭会话。</p>
</li>
</ol>
<p>所以得出的结论是,refresh_token是一个很巧妙地设计,提升了用户体验的同时,又保证了安全性。另外,在OAuth 2.0安全最佳实践中,推荐refresh_token是一次性的,什么意思呢?使用refresh_token获取access_token时,同时会返回一个新的refresh_token,之前的refresh_token就会失效,但是两个refresh_token的绝对过期时间是一样的,所以不会存在refresh_token快过期就获取一个新的,然后重复,永不过期的情况。</p>
<p><strong>Access &#x2F; Refresh Token如何使用</strong>？</p>
<ol>
<li><p>用户提供身份信息（一般是用户名密码），利用客户端向认证服务器换取Refresh Token和Access Token；</p>
</li>
<li><p>客户端携带Access Token访问资源服务器，资源服务器识别Access Token并返回资源；</p>
</li>
<li><p>当Access Token过期或失效，客户端再一次访问资源服务器，资源服务器返回“无效token”报错；</p>
</li>
<li><p>客户端通过Refresh Token向认证服务器换取Access Token，认证服务器返回新的Access Token。</p>
</li>
</ol>
<p>用一个现实生活中的比喻来解释Access&#x2F;Refresh Token的使用过程：假设我在网上预定了一家酒店。如果要入住这家酒店，我必须出示身份证和订单。酒店前台会登记相关证件和订单信息，确认无误后会给我一张票据和一张房卡（票据记录我需要入住多少天，而房卡则让我有当天的入住权）。以上场景中，“身份证和订单”是我的用户名密码，“票据&#x2F;房卡”是Refresh&#x2F;Access Token，“前台”是认证服务器，“房间”是资源服务器。在整个入住过程中，“身份证和订单”只在前台使用一次；实际能进入房间的是“房卡”，但是房卡只有一天的有效期；如果房卡过期，我需要凭“票据”去前台刷新“房卡”，获取第二天的入住权。将Token拆分成两个，就是为了解决安全性和用户体验方面的矛盾—Access Token使用频繁，且与用户数据直接关联，安全性方面比较敏感，因此有效期设置得较短，即使Access Token泄漏也将很快失效。利用过期时间较短这个特性，也可以及时更新用户的访问权限（比如管理员缩小了的某员工访问公司数据的权限，当Token过期后换取的新Access Token将立马缩小其访问数据的权限）。而Refresh Token仅用于获取新的Access Token，使用频率较低，不与用户数据直接关联，过期时间允许设置得长一些。这样就解决了用户反复登录的问题。</p>
<h3 id="相关文章"><a href="#相关文章" class="headerlink" title="相关文章"></a>相关文章</h3><table>
<thead>
<tr>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/i8hvrKPSCwlzpmt_p52ZbA">妹子始终没搞懂OAuth 2.0，今天整合Spring Cloud Security一次说明白！</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/l1vll9aSL1IzjsI-DhbtUw">快速接入GitHub、QQ第三方登录真有那么难吗？</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/S7NNeiPJAEtNQtypxrWcmw">Spring Security OAuth2整合企业微信扫码登录</a></th>
</tr>
</thead>
<tbody><tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/r0H5zsm2H0AZui5nfeElRw">实战：画了几张图，终于把OAuth2搞清楚了</a></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/blog/about" rel="external nofollow noreferrer">xmxe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://xmxe.github.io/blog/posts/8c045b869342/">https://xmxe.github.io/blog/posts/8c045b869342/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/blog/about" target="_blank">xmxe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/blog/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,douban" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/blog/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        
                            <img src="/blog/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                        
                    </div>
                    <div id="wechat">
                        
                            <img src="/blog/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/blog/posts/a31926113ddc/">
                    <div class="card-image">
                        
                        <img src="https://pic1.zhimg.com/v2-3ec9f9b98b4c3596e09b40d143410f0e_1440w.jpg" class="responsive-img" alt="Redis详解">
                        
                        <span class="card-title">Redis详解</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            3种常用的缓存读写策略详解Cache Aside Pattern（旁路缓存模式）Cache Aside Pattern是我们平时使用比较多的一个缓存读写模式，比较适合读请求比较多的场景。Cache Aside Pattern中服务端需要同时
                        

                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2022-11-15
                            -->

                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                        数据库
                                    </a>
                                
                            

                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/blog/posts/38f9e76ec464/">
                    <div class="card-image">
                        
                        <img src="https://picd.zhimg.com/v2-de9bcd56c1670f877189df89ded47289_1440w.jpg" class="responsive-img" alt="ElasticSearch详解">
                        
                        <span class="card-title">ElasticSearch详解</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            



第1章 Elasticsearch概述




01-开篇
02-技术选型
03-教学大纲








第2章 Elasticsearch入门



04-入门-环境准备
05-入门-RESTful &amp; JSON
06-
                        
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2022-11-15
                            -->
                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                        数据库
                                    </a>
                                
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/blog/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="569200213"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/blog/libs/aplayer/APlayer.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script> -->

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
            
                <span id="year">2022-2025
                </span>
            
            

            <a href="/blog/about" target="_blank">
                xmxe
            </a>
            |&nbsp;Powered by&nbsp;
            <a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>

            
            
            
            
            
            

            
            <br>

            
            <br>

            
        </div>
        <div class="col s12 m4 l4 social-link2 ">
    <a href="https://github.com/xmxe" class="tooltipped" target="_blank" data-tooltip="GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/xmxe" class="tooltipped" target="_blank" data-tooltip="码云" data-position="top" data-delay="50">
        <svg width="19" height="19" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" style="position: relative; top: 2px; left: 0.5px;">
            <path d="M512 1024C230.4 1024 0 793.6 0 512S230.4 0 512 0s512 230.4 512 512-230.4 512-512 512z m259.2-569.6H480c-12.8 0-25.6 12.8-25.6 25.6v64c0 12.8 12.8 25.6 25.6 25.6h176c12.8 0 25.6 12.8 25.6 25.6v12.8c0 41.6-35.2 76.8-76.8 76.8h-240c-12.8 0-25.6-12.8-25.6-25.6V416c0-41.6 35.2-76.8 76.8-76.8h355.2c12.8 0 25.6-12.8 25.6-25.6v-64c0-12.8-12.8-25.6-25.6-25.6H416c-105.6 0-188.8 86.4-188.8 188.8V768c0 12.8 12.8 25.6 25.6 25.6h374.4c92.8 0 169.6-76.8 169.6-169.6v-144c0-12.8-12.8-25.6-25.6-25.6z" fill="#fff">
            </path>
        </svg>
    </a>

















    
        
          <a href="/blog/download" class="tooltipped" target="_blank" data-tooltip="下载" data-position="top" data-delay="50">
            <i class="fas fa-download"></i>
          </a>
        
    



    <style>
  .mobiledevice {
    display: none !important;
  }

  footer .wechat_qrcode {
    position: fixed;
  }

  /*微信二维码*/
  .wechat_qrcode {
    position: absolute;
    margin-left: 10px;
    bottom: 10px;
    background: url("/blog/medias/xcx.png");
    zoom:40%;
  }

  .wechat:hover .wechat_qrcode {
    width: 430px;
    height: 430px;
    animation: move 0.4s linear 1 normal;
  }

  @keyframes move {
    0% {
      transform: translate(100px, 0);
      opacity: 0;
    }
    50% {
      transform: translate(50px, 0);
      opacity: 0.5;
    }
    100% {
      transform: translate(0, 0);
      opacity: 1;
    }
  }

  @media only screen and (max-width: 601px) {
    .wechat {
      display: none !important;
    }
    .mobiledevice {
      display: inline-block !important;
    }
  }
</style>

<a href="javascript:;" class="wechat" data-position="top" data-delay="50">
  <i class="fab fa-weixin"></i>
  <img class="wechat_qrcode" />
</a>

<a
  href="javascript:;"
  class="tooltipped mobiledevice"
  data-tooltip="微信: 464817304"
  data-position="top"
  data-delay="50"
>
  <i class="fab fa-weixin"></i>
</a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/blog/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>

    <div class="stars-con">
  <div id="stars"></div>
  <div id="stars2"></div>
  <div id="stars3"></div>  
</div>

<!-- 白天和黑夜主题 -->



<script>
  function switchNightMode() {
    
      setTimeout(function () {
        $('body').hasClass('DarkMode') 
        ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
        : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
          
        setTimeout(function () {
          $('.Cuteen_DarkSky').fadeOut(1e3, function () {
            $(this).remove()
          })
        }, 2e3)
      })
  }
</script>
    
    
    <script>
        /* 模式判断 */
        if (localStorage.getItem('isDark') === '1') {
            document.body.classList.add('DarkMode');
            $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')
        } else {
            document.body.classList.remove('DarkMode');
            $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')
        }
    </script>

    <script src="/blog/libs/materialize/materialize.min.js"></script>
    <script src="/blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/blog/libs/aos/aos.js"></script>
    <script src="/blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    

    

    

	
    

    

    
    <script type="text/javascript" src="/blog/libs/background/ribbon-dynamic.js" async="async"></script>
    

    

    <!-- 冒泡 -->
    
    <script type="text/javascript">
        // 只在桌面版网页启用特效
        // var windowWidth = $(window).width();
        
            document.write('<script type="text/javascript" src="/blog/libs/others/bubleAll.js"><\/script>');
        
        
    </script>
    

    <!-- 弹出文字 -->
    

</body>

</html>
